<template>
  <div class="container">
    <el-card class="courseBox-card">
      <el-tabs v-model="activeName">
        <el-tab-pane label="我学的课" name="first">
          <div class="courseList">
            <!-- 课程操作 -->
            <div class="courseOpt">
              <div class="btu">
                <el-popover
                  placement="right"
                  :width="200"
                  v-model:visible="visible"
                  title="添加"
                  trigger="click"
                >
                  <template #reference>
                    <el-button type="primary" size="large" round
                      >+加入课程</el-button
                    >
                  </template>
                  <div>
                    <el-input
                      v-model="courseCode"
                      placeholder="输入课程码"
                    ></el-input>
                  </div>
                  <div style="text-align: right; margin-top: 10px">
                    <el-button size="small" text @click="visible = false"
                      >取消</el-button
                    >
                    <el-button size="small" type="primary" @click="addCourse()"
                      >确认</el-button
                    >
                  </div>
                </el-popover>
                <el-popover placement="right" :width="400" trigger="hover">
                  <template #reference>
                    <el-button type="primary" size="large" round
                      >选课记录表</el-button
                    >
                  </template>
                  <el-table :data="recordSheet">
                    <el-table-column width="150" property="name" label="课程" />
                    <el-table-column
                      width="100"
                      property="teacher"
                      label="老师"
                    />
                    <el-table-column
                      width="200"
                      property="school"
                      label="学校"
                    />
                  </el-table>
                </el-popover>
              </div>
              <div class="serach">
                <el-input
                  v-model="search1"
                  class="w-50 m-2"
                  size="large"
                  placeholder="搜索"
                  suffix-icon="search"
                >
                </el-input>
              </div>
            </div>
            <!-- 课程布局 -->
            <div class="courses">
              <div v-if="filterLearingCourseList.length == 0">
                <el-empty
                  :image-size="200"
                  description="快来加入课程学习吧！"
                />
              </div>
              <div
                class="courseItem"
                v-for="(item, index) in filterLearingCourseList"
                :key="index"
              >
                <div class="course-cover">
                  <!-- 点击图片进行跳转到课程详细页面 -->
                  <div @click="testClick(item.id)">
                    <el-image :src="item.cover" fit="fill" class="course-cover">
                      <template #error>
                        <div class="image-slot">
                          <el-icon><PictureFilled /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>
                <div class="course-info">
                  <h3 class="inlineBlock">
                    <a
                      href="javascript:void(0)"
                      @click="testClick(item.id)"
                      class="color1"
                    >
                      <span>{{ item.name }}</span>
                    </a>
                  </h3>
                  <p class="line2" :title="item.school">{{ item.school }}</p>
                  <p class="line2 color3" :title="item.teacher">
                    {{ item.teacher }}
                  </p>
                  <p>
                    开课时间：{{ getCurrentTime(item.createTime) }}～{{
                      getCurrentTime(item.end)
                    }}
                  </p>
                  <p class="overHidden1">班级：{{ item.openClass }}</p>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我教的课" name="second">
          <div class="courseList">
            <!-- 课程操作 -->
            <div class="courseOpt">
              <div class="btu">
                <el-button
                  v-if="role == 'teacher'"
                  type="primary"
                  round
                  size="large"
                  @click="uploadFile"
                  >+批量导入
                </el-button>
                <el-button
                  v-if="role == 'teacher'"
                  type="primary"
                  round
                  size="large"
                  @click="openCreat()"
                  >+创建课程</el-button
                >
              </div>
              <div class="serach">
                <el-input
                  v-model="search2"
                  class="w-50 m-2"
                  size="large"
                  placeholder="搜索"
                  suffix-icon="search"
                >
                </el-input>
              </div>
            </div>
            <el-dialog title="上传文件" v-model="dialogFormVisible">
              <!-- 需要考虑的是两个内容 接口 和附带的参数 -->
              <el-upload
                class="upload-demo"
                drag
                ref="uploadDemo"
                :headers="headerObj"
                action="http://localhost:8080/api//user/import"
                :file-list="fileList"
                :on-success="uploadSuccess"
                :on-error="uploadFail"
                :limit="1"
                :on-exceed="exceed"
                :auto-upload="false"
                multiple
                accept=".xls,.xlsx"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  Drop file here or <em>click to upload</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    files with a size less than 10G
                    <el-button
                      size="small"
                      style="margin-left: 50px"
                      @click="dialogFormVisible = false"
                      >取 消</el-button
                    >
                    <el-button size="small" type="primary" @click="upload1"
                      >确 定</el-button
                    >
                  </div>
                </template>
              </el-upload>
            </el-dialog>
            <!-- 课程布局 -->
            <div class="courses">
              <div v-if="filterTeachingCourseList.length == 0">
                <el-empty
                  :image-size="200"
                  description="快来创建你的课程吧！"
                />
              </div>
              <div
                class="courseItem"
                v-for="(item, index) in filterTeachingCourseList"
                :key="index"
              >
                <div>
                  <!-- 点击图片进行跳转到课程详细页面 -->
                  <div @click="testClick(item.id)">
                    <el-image :src="item.cover" fit="fill" class="course-cover">
                      <template #error>
                        <div class="image-slot">
                          <el-icon><PictureFilled /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>
                <div class="course-info">
                  <h3 class="inlineBlock">
                    <a
                      href="javascript:void(0)"
                      @click="testClick(item.id)"
                      class="color1"
                    >
                      <span>{{ item.name }}</span>
                    </a>
                  </h3>
                  <p class="line2" :title="item.school">{{ item.school }}</p>
                  <p class="line2 color3" :title="item.teacher">
                    {{ item.teacher }}
                  </p>
                  <p>
                    开课时间：{{ getCurrentTime(item.createTime) }}～{{
                      getCurrentTime(item.end)
                    }}
                  </p>
                  <p class="overHidden1">班级：{{ item.openClass }}</p>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="所有课程" name="third">
          <div class="courseList">
            <!-- 课程操作 -->
            <div class="courseOpt">
              <div class="serach">
                <el-input
                  v-model="search3"
                  class="w-50 m-2"
                  size="large"
                  placeholder="搜索"
                  suffix-icon="search"
                >
                </el-input>
              </div>
            </div>
            <!-- 课程布局 -->
            <div class="courses">
              <div v-if="filterAllCourseList.length == 0">
                <el-empty :image-size="200" description="暂时还没有课程！" />
              </div>
              <div
                class="courseItem"
                v-for="(item, index) in filterAllCourseList"
                :key="index"
              >
                <div>
                  <div @click="joinToCourse(item.id)">
                    <el-image :src="item.cover" fit="fill" class="course-cover">
                      <template #error>
                        <div class="image-slot">
                          <el-icon><PictureFilled /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>
                <div class="course-info">
                  <h3 class="inlineBlock">
                    <a
                      href="javascript:void(0)"
                      @click="joinToCourse(item.id)"
                      class="color1"
                    >
                      <span>{{ item.name }}</span>
                    </a>
                  </h3>
                  <p class="line2" :title="item.school">{{ item.school }}</p>
                  <p class="line2 color3" :title="item.teacher">
                    {{ item.teacher }}
                  </p>
                  <p>
                    开课时间：{{ getCurrentTime(item.createTime) }}～{{
                      getCurrentTime(item.end)
                    }}
                  </p>
                  <p class="overHidden1">班级：{{ item.openClass }}</p>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 新增课程 -->
    <el-dialog v-model="dialogVisible" title="创建课程" width="40%" center>
      <el-form :model="course" label-width="120px">
        <el-form-item label="课程名称">
          <el-input v-model="course.name" />
        </el-form-item>
        <el-form-item label="课程时间">
          <el-col :span="12">
            <el-date-picker
              v-model="course.start"
              type="date"
              value-formate="timestamp"
              placeholder="开始时间"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="12">
            <el-date-picker
              v-model="course.end"
              type="date"
              value-formate="timestamp"
              placeholder="结束时间"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="是否付费">
          <el-col :span="10">
            <el-switch v-model="isPay" />
          </el-col>
          <el-col :span="4" v-show="isPay">
            <span>价格：</span>
          </el-col>
          <el-col :span="10" v-show="isPay">
            <el-input-number
              v-model="course.price"
              :precision="2"
              :step="0.1"
              :max="10"
            />
          </el-col>
          <!-- 付费的话再添加选择价格 -->
        </el-form-item>
        <el-form-item label="课程标签">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="ml-1 w-20"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag ml-1"
            size="small"
            @click="showInput"
          >
            + New Tag
          </el-button>
        </el-form-item>
        <el-form-item label="开课班级">
          <el-input v-model="course.openClass" />
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input v-model="course.introduction" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="cancelEvent">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  defaultAddCourse,
  queryCourseByUserId,
  queryCourseByTeacherId,
  getAllCourses,
} from "@/api/course";
import { joinCourse, queryByStudentId } from "@/api/user.js";
import { mapGetters } from "vuex";
import { reactive, ref, nextTick, getCurrentInstance } from "vue";
import { ElMessage, ElNotification } from "element-plus";
export default {
  setup() {
    const { proxy } = getCurrentInstance();
    const dialogVisible = ref(false);
    const isPay = ref(0);
    const InputRef = ref();
    const course = reactive({
      cover: "",
      createTime: "",
      end: "", //课程结束时间
      id: "", //课程ID
      introduction: "", //课程简介
      name: "", //课程名称
      openClass: "", //开课班级
      price: 0,
      school: "",
      start: "",
      tags: "",
      teacher: "", //任课老师默认为创建课程的老师
    });
    const inputValue = ref("");
    const dynamicTags = ref([]);
    const inputVisible = ref(false);
    const handleClose = (tag) => {
      dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
    };
    const showInput = () => {
      inputVisible.value = true;
      nextTick(() => {
        InputRef.value.input.focus();
      });
    };
    const handleInputConfirm = () => {
      if (inputValue.value) {
        dynamicTags.value.push(inputValue.value);
      }
      inputVisible.value = false;
      inputValue.value = "";
    };
    const onSubmit = () => {
      let temp = dynamicTags.value.join("/") + "/";
      course.tags = temp;
      course.teacher = proxy.realName;
      course.school = proxy.school;
      defaultAddCourse(course, proxy.tid).then((res) => {
        if (res.code == "200") {
          proxy.teachingCourseList.push(res.data);
          dialogVisible.value = false;
          ElMessage({
            type: "success",
            message: "创建成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "创建失败",
          });
        }
      });
    };
    const cancelEvent = () => {
      dialogVisible.value = false;
    };
    return {
      dialogVisible,
      course,
      isPay,
      inputValue,
      dynamicTags,
      inputVisible,
      InputRef,
      handleClose,
      showInput,
      handleInputConfirm,
      onSubmit,
      cancelEvent,
    };
  },

  // 数据源
  data() {
    return {
      activeName: "first",
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 课程搜索框  前端做模拟 过滤器
      search1: "",
      search2: "",
      search3: "",
      visible: false,
      dialogFormVisible: false,
      courseList: [],
      teachingCourseList: [],
      courseCode: "",
      recordSheet: [],
      fileList: [],
      allCourseList: [],
    };
  },
  created() {
    this.dynamicTags.push(this.school);
    this.getCourseList();
    this.getTeachingCourseList();
    this.getAllCourse();
  },
  //生命周期函数---
  mounted() {},
  //基本方法
  methods: {
    getCurrentTime(stamp) {
      let time;
      if (stamp !== undefined) {
        time = new Date(stamp);
      } else {
        time = new Date();
      }
      let d = time.toLocaleDateString();
      return `${d} `;
    },
    // 点击事件，加入课程
    addCourse() {
      if (this.courseCode == "") {
        ElMessage({
          type: "info",
          message: "请先输入课程码",
        });
        return;
      } else {
        joinCourse(this.courseCode, "", this.tid).then((res) => {
          // console.log(res);
          if (res.code == "200") {
            this.visible = false;
            ElMessage({
              type: "success",
              message: "加入成功",
            });
          } else {
            this.visible = false;
            this.courseCode = "";
            ElMessage({
              type: "error",
              message: "加入失败",
            });
          }
        });
      }
    },
    openCreat() {
      this.dialogVisible = true;
    },
    // 点击事件 进入课程空间,难点是怎么在url中携带课程ID参数并能够在目标页面解析
    testClick(id) {
      this.$router.push({
        name: "announcement",
        query: {
          courseId: id,
        },
      });
    },
    //自己所上的课程
    getCourseList() {
      queryCourseByUserId(this.tid).then((res) => {
        if (res.code == "200") {
          this.courseList = res.data;
        }
        return res.code
      }).then((res,req)=>{
        if(res==200)
          this.qwe()
      });
    },
    //老师自己所开的课程
    getTeachingCourseList() {
      queryCourseByTeacherId(this.tid).then((res) => {
        if (res.code == "200") {
          this.teachingCourseList = res.data;
        }
      });
    },
    //所有开设的课程
    getAllCourse() {
      getAllCourses("1", "100").then((res) => {
        if (res.code == 200) {
          this.allCourseList = res.data;
        } else {
          ELMessage({
            type: "error",
            message: "获取所有课程失败",
          });
        }
      });
    },
    qwe() {
      queryByStudentId(this.tid).then((res) => {
        if (res.code == "200") {
          this.recordSheet = res.data;
        }
      });
    },
    uploadSuccess(response) {
      console.log(response);
      console.log(arguments);
      this.fileList = [];
      this.dialogFormVisible = false;
      ElMessage({
        type: "success",
        message: "批量操作成功",
      });
      if (response.code == 200) {
        ElNotification({
          title: "success",
          message: "所有数据都成功导入",
          type: "success",
        });
      } else {
        response.data.forEach((item) => {
          setTimeout(() => {
            ElNotification({
              title: "Error",
              message: item,
              type: "Error",
              offset: 100,
            });
          }, 2000);
        });
      }
    },
    //上传失败的回调
    uploadFail() {
      ElMessage({
        type: "error",
        message: "批量上传失败",
      });
      this.fileList = [];
    },
    uploadFile() {
      this.dialogFormVisible = true;
    },
    // 对选中文件进行上传
    upload1() {
      //手动提交上传
      this.$refs.uploadDemo.submit();
    },
    exceed() {
      ElMessage({
        type: "warning",
        message: "一次只能批量处理一个文件",
      });
    },

    //在所有课程列表中选择加入课程相关操作
    joinToCourse(cid) {
      if (confirm(`确定加入课程？`)) {
        joinCourse(cid, "", this.tid).then((res) => {
          console.log(res);
          if (res.code == "200") {
            this.visible = false;
            ElMessage({
              type: "success",
              message: "加入成功",
            });

          } else {
            this.visible = false;
            this.courseCode = "";
            ElMessage({
              type: "error",
              message: res.reason,
            });
          }
          return res.code
        }).then((res,req)=>{
          if(res!=-1)
            this.getCourseList()
        })
      } else {
        ElMessage({
          type: "info",
          message: "已取消",
        });
      }
    },
  },
  //计算类型方法和其他方法的区别：有缓存。以内存换时间，适用于频繁使用的计算
  computed: {
    ...mapGetters({
      role: "getRole",
      school: "getSchool",
      realName: "getRealName",
      tid: "getId",
    }),
    filterLearingCourseList() {
      return this.courseList.filter(
        (item) =>
          !this.search1 ||
          item.name.toLowerCase().includes(this.search1.toLowerCase())
      );
    },
    filterTeachingCourseList() {
      return this.teachingCourseList.filter(
        (item) =>
          !this.search2 ||
          item.name.toLowerCase().includes(this.search2.toLowerCase())
      );
    },
    filterAllCourseList() {
      return this.allCourseList.filter(
        (item) =>
          !this.search3 ||
          item.name.toLowerCase().includes(this.search3.toLowerCase())
      );
    },
  },
  watch: {
    role: {
      handler(val) {
        if (val == "teacher") {
          this.activeName = "second";
        } else {
          this.activeName = "first";
        }
      },
      immediate: true,
    },
  },
};
</script>
<style  scoped>
.courseBox-card {
  margin-top: 30px;
  width: 85%;
  border-radius: 10px;
}
.el-tabs__content {
  min-height: 700px;
}
.courseOpt {
  display: flex;
  justify-content: space-between;
}

.serach {
  border-radius: 10px;
}

.courses {
  min-height: 600px;
}
.courseItem {
  float: left;
  width: 240px;
  height: 300px;
  font-size: 12px;
  box-sizing: border-box;
  vertical-align: top;
  color: #a8a8b3;
  overflow: visible;
  cursor: pointer;
  margin-left: 40px;
  margin-bottom: 0;
  margin-top: 20px;
}
.course-cover {
  width: 240px;
  height: 130px;
  border-radius: 8px;
  position: relative;
  margin-bottom: 12px;
}

.course-cover:hover {
  -webkit-box-shadow: #ccc 0px 10px 10px;
  -moz-box-shadow: #ccc 0px 10px 10px;
  box-shadow: 5px -5px 17px -3px #c4b8ba;
}

.course-cover > a img {
  display: inline-block;
  width: 100%;
  height: 100%;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  border-radius: 8px;
}

.course-info {
  box-sizing: border-box;
  padding: 0 6px;
  text-align: left;
}

.inlineBlock {
  display: inline-block;
  width: 100%;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}

h3 {
  margin: 0 0;
}

.color1 {
  color: #131b26;
}

a {
  text-decoration: none;
}

a:hover {
  color: rgb(58, 139, 255);
}

.line2 {
  overflow: hidden;
  text-overflow: ellipsis;
  color: #474c59;
  margin-top: 10px;
}

.color3 {
  color: #8a8b99;
}

.overHidden1 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.mx-1,
.ml-1 {
  margin-left: 8px;
  margin-bottom: 8px;
}
.w-20 {
  width: 80px;
}
.image-slot {
  font-size: 140px;
}
</style>